package com.wkk.service.impl;

import com.wkk.entity.*;
import com.wkk.mapper.AdminMapper;
import com.wkk.mapper.CoachMapper;
import com.wkk.mapper.CourseMapper;
import com.wkk.service.CourseService;
import com.wkk.util.GeneralCalculation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private CoachMapper coachMapper;


    @Override
    public boolean addCourse(Course course) {
        int i = 0;
        //判断是否出现同时间同地点的课程，如果出现则无法添加，并反馈信息
        List<Course> courses = courseMapper.selectList();
        for(Course course1:courses){
            if(course1.getSchooltime().equals(course.getSchooltime())&&course1.getVenue().equals(course.getVenue())&&course1.getWeek()==course.getWeek()){
                //判断是否出现同时间同地点的课程，如果出现则无法添加，并反馈信息
                i = 2;
            }
        }
        if(i == 0){
            i = courseMapper.insertCourse(course);
        }
        return i==1?true:false;
    }

    @Override
    public boolean deleteCourseByCid(Integer cid) {
        int i = 0;
        if(courseMapper.queryMyCoursesByCid(cid).size()>0){
            return false;//如果该课程有人在上，则无法删除
        }else {
            i = courseMapper.deleteCourse(cid);
        }
        return i==1?true:false;
    }

    @Override
    public boolean updateCourse(Course course) {
        int i = 0;
        List<Course> courses = courseMapper.selectList();
       // System.out.println(courses);
        courses.remove(courseMapper.selectOne(course.getCid()));//移除本身
       // System.out.println(courseMapper.selectOne(course.getCid()));
        //System.out.println(courses);
        for(Course course1:courses){
            if(course1.getSchooltime().equals(course.getSchooltime())&&course1.getVenue().equals(course.getVenue())&&course1.getWeek()==course.getWeek()){
                //判断是否出现同时间同地点的课程，如果出现则无法更新，并反馈信息
                i = 2;
            }
        }
        if(i == 0) {
            i = courseMapper.updateCourse(course);
        }
        return i==1?true:false;
    }

    @Override
    public List<Course> selectListByMoldOrTeacher(String searchValue) {
        if(searchValue==null){
            return courseMapper.selectListByNotPublic();
        }
        List<Course> courses = courseMapper.selectListByTeacher(searchValue);
        if(courses.size()==0){
            courses = courseMapper.selectListByMold(searchValue);
        }
        return courses;
    }

    @Override
    public List<Course> orderBySearchCount() {
        String info = "searchCount";
        return courseMapper.selectListOrderBy(info);
    }

    @Override
    public List<Course> orderByOrderCount() {
        String info = "orderCount";
        return courseMapper.selectListOrderBy(info);
    }

    @Override
    public List<Course> selectList() {
        return courseMapper.selectList();
    }

    @Override
    public Course selectOne(Integer cid) {
        return courseMapper.selectOne(cid);
    }

    @Override
    public boolean updateCount(String key,Integer cid) {
        int i = 0;
        Map<String,Object> map = new HashMap<>();
        map.put("countName",key);
        map.put("cid",cid);
        i = courseMapper.updateSearchCountOrOrderCount(map);
        return i==1?true:false;
    }

    @Override
    public boolean achieveCourse(Integer cid) {
        int i = 0;
        i = courseMapper.updateCourseAchieveMan(cid);
        return i == 1?true:false;
    }

    @Override
    public PageBean<Course> pageByCondition(String condition, Integer current) {
        Map<String,Object> map = new HashMap<>();
        PageBean<Course> pageBean = new PageBean<>();
        pageBean.setCurrent(current);
        map.put("condition",condition);
        int pageSize = 10;//每页用户数
        pageBean.setSize(pageSize);
        int total = courseMapper.countByCondition(condition).size();//满足条件的总用户数
        pageBean.setTotal(total);
        double tc = total;
        Double pages = Math.ceil(tc/pageSize);//向上取整
        pageBean.setPages(pages.intValue());//总页数
        map.put("start",(current-1)*pageSize);//分页查询的起始点
        map.put("size",pageBean.getSize());//分页查询的用户长度
        pageBean.setRecords(courseMapper.selectListByCondition(map));
        return pageBean;
    }

    @Override
    public PageBean<Course> pageByQuery(Course course, Integer current) {
        Map<String,Object> map = new HashMap<>();
        PageBean<Course> pageBean = new PageBean<>();
        pageBean.setCurrent(current);
        map.put("course",course);
        int pageSize = 10;//每页用户数
        pageBean.setSize(pageSize);
        int total = courseMapper.countByQuery(course).size();//满足条件的总用户数
        pageBean.setTotal(total);
        double tc = total;
        Double pages = Math.ceil(tc/pageSize);//向上取整
        pageBean.setPages(pages.intValue());//总页数
        map.put("start",(current-1)*pageSize);//分页查询的起始点
        map.put("size",pageBean.getSize());//分页查询的用户长度
        pageBean.setRecords(courseMapper.selectListByQuery(map));
        return pageBean;
    }


    @Override
    public boolean addToMyCourse(MyCourse myCourse,Integer sign) {

        //声明这个年份月份的业绩---用于查询
        Calendar calendar = Calendar.getInstance();
        Course course1 = courseMapper.selectOne(myCourse.getCid());
        Coach coach = coachMapper.selectOneByName(course1.getTeacher());
        CoachPerformance nowPerformance = new CoachPerformance(coach.getCid(),calendar.get(Calendar.MONTH) + 1,calendar.get(Calendar.YEAR));
        nowPerformance.setCourseCount(myCourse.getClassNum());
        CoachPerformance coachPerformance = coachMapper.selectOneP(nowPerformance);
        if(coachPerformance==null){//如果当年当月的该教练业绩不存在，则先添加此业绩,再进行更新课时数
            coachMapper.insertPerformance(nowPerformance);
            CoachPerformance coachPerformance1 = coachMapper.selectOneP(nowPerformance);
            coachPerformance1.setCourseCount(myCourse.getClassNum());
            coachMapper.updatePCourseCount(coachPerformance1);
        }else{
            coachPerformance.setCourseCount(myCourse.getClassNum());
            coachMapper.updatePCourseCount(coachPerformance);//连接成功后更新本月教练的课时数
        }
        //该部分实现：会员购买指定教练的课程，则该教练的私教课时数就加上购买的课时数

        //同时将该收入加入收入表
        Income income = new Income();
        if(course1.getMold().equals("特色课")){
            income.setType("特色课收入");
        }else if(course1.getMold().equals("康复课")){
            income.setType("康复课收入");
        }else{
            income.setType("私教课收入");
        }
        income.setMoney(myCourse.getClassNum()*courseMapper.selectOne(myCourse.getCid()).getPrice());

        adminMapper.insertOneIncome(income);

        int i = 0;
        myCourse.setState(sign);
        //如果该课已被购买，则课时直接叠加
        List<MyCourse> myCourses = courseMapper.queryMyCourses(myCourse.getUid());
        for(MyCourse course:myCourses){
            if(course.getCid()==myCourse.getCid()&&course.getUid()==myCourse.getUid()&&course.getState()==myCourse.getState()){
                myCourse.setClassNum(course.getClassNum()+myCourse.getClassNum());
                myCourse.setId(course.getId());
                courseMapper.updateMyCourse(myCourse);
                i = 1;
            }
        }


        if(i==0&&sign==0){//会员自主购买
            i = courseMapper.insertMyCourse(myCourse);
        }
        if(i==0&&sign==1){//教练预购
            i = courseMapper.insertMyCourseByCoach(myCourse);
        }
        return  i == 1?true:false;
    }

    @Override
    public boolean deleteMyCourseById(Integer cid) {
        int i = 0;
        i = courseMapper.deleteMyCourse(cid);
        return  i == 1?true:false;
    }

    @Override
    public boolean updateMyCourse(MyCourse myCourse) {
        int i = 0;
        i = courseMapper.updateMyCourse(myCourse);
        return  i == 1?true:false;
    }

    @Override
    public List<MyCourse> queryMyCoursesById(Integer uid) {
        List<MyCourse> courses = courseMapper.queryMyCourses(uid);
        GeneralCalculation generalCalculation = new GeneralCalculation();
        for(MyCourse myCourse:courses){
            myCourse.setCourse(courseMapper.selectOne(myCourse.getCid()));
            MyCourseSign myCourseSign = courseMapper.selectOneByMyId(myCourse.getId());
            if(myCourseSign==null){
                //没签到过,或者之前签到的时间与今天不相等
                myCourse.setSignState(0);
            }else {
                if(generalCalculation.judgeDate(myCourseSign.getDate())!=0){
                    myCourse.setSignState(0);
                }else{
                myCourse.setSignState(1);
                }
            }

        }

        return courses;
    }

    @Override
    public boolean updateMyCourseState(Integer id) {
        int i = 0 ;
        i = courseMapper.updateMyCourseState(id);
        return i == 1?true:false;
    }

    @Override
    public MyCourse selectOneMC(Integer id) {
        MyCourse myCourse = courseMapper.selectOneById(id);
        myCourse.setCourse(courseMapper.selectOne(myCourse.getCid()));
        return myCourse;
    }

    @Override
    public boolean addOrUpdateHistory(Course course, Integer uid) {
        int i = 0;
        MyHistory myHistory = new MyHistory(uid,course.getCid(),course.getMold());
         if(courseMapper.selectOneByUidAndMold(myHistory)==null){
            i =  courseMapper.insertHistory(myHistory);
         }else{
            i = courseMapper.addSearchCountInMyHistory(myHistory);
         }
        return i==1?true:false;
    }

    @Override
    public List<Course> desktopAboutCourse(Integer uid) {
        List<Course> courses = new ArrayList<>();
        List<Course> courses1 = courseMapper.selectListOrderBy("searchCount");
        List<MyHistory> myHistories = courseMapper.selectListByUid(uid);
        if(myHistories.size()==0){
           courses.add(courses1.get(0));
           courses.add(courses1.get(1));
           courses.add(courses1.get(2));

        }else{
            for(MyHistory history:myHistories){
                List<Course> courses2 = courseMapper.selectListByMold(history.getMold());
                if (courses2.size() >= 3-courses.size()) {
                    for(int i = 0;i<courses2.size();i++){
                        courses.add(courses2.get(i));
                        if(courses.size()>=3){
                            return courses;
                        }
                    }
                } else {
                    for (Course course : courses2) {
                        courses.add(course);
                    }
                }
                if(courses.size()>=3){
                    return courses;
                }
            }
        }
        int size = courses.size();
        if(size==1) {
            for(int i = 0; i < courses1.size(); i++) {
                if(courses1.get(i).getCid()==courses.get(0).getCid()){
                    continue;
                }
                courses.add(courses1.get(i));
                if(courses.size()>=3){
                    return courses;
                }
            }
        }else if(size==2){
            for (int i = 0; i < courses1.size(); i++) {
                if(courses1.get(i).getCid()==courses.get(0).getCid()||courses1.get(i).getCid()==courses.get(1).getCid()){
                    continue;
                }
                 courses.add(courses1.get(i));
                if(courses.size()>=3){
                    return courses;
                }
            }
        }else if(size==0){
            for (int i = 0; i < 3; i++) {
                courses.add(courses1.get(i));
            }
        }

        return courses;
    }

    @Override
    public boolean addOrUpdateMySign(Integer id) {
        int i = 0;
        MyCourseSign myCourseSign = courseMapper.selectOneByMyId(id);
        if(myCourseSign==null){
          i = courseMapper.insertSignIn(id);
        }else{
            i = courseMapper.updateDateById(id);
        }
        courseMapper.updateMyCourseLastNum(id);//并将课时减少
        //如果课时为0则将该课程结束
        if(courseMapper.selectOneById(id).getNumLast()==0){
            courseMapper.updateMyCourseState(id);
        }
        return i==1?true:false;
    }


}
